const Koa = require('koa');
const koaBody = require('koa-body');
const router = require('koa-router')();

const config = require('./config/config');
const userRouter = require('./router/user');
const accountRouter = require('./router/account');
const validToekn = require('./dbs/user');
require('./libs/DBConect');
require('./libs/redisConect');
const log = require('./libs/log4js')('APP');
const sendEmail = require('./libs/sendEmail');


const app = new Koa();

app.use(koaBody({
  multipart: true,
  formidable: {
    maxFileSize: 200 * 1024 * 1024 // 设置上传文件大小最大限制，默认2M
  }
}));

app.use(async (ctx, next) => {
  const res = ctx.request;
  log.info(`${res.method}`, `${res.url}, ${JSON.stringify(res.body || ctx.query)}`);
  await next();
  ctx.set({
    'Content-Type': 'application/json'
  });
  if (!ctx.body) {
    ctx.body = JSON.stringify({
      code: 404,
      data: '',
      msg: '服务器繁忙'
    });
  }
  if (res.url.indexOf('/log') > -1) return;
  log.info('reqbody', ctx.body);
});

app.use(async (ctx, next) => {
  const res = ctx.request;
  if (res.url.split('/')[2] !== 'user') {
    let auth = res.headers.auth;
    if (!auth) {
      ctx.body = JSON.stringify({
        code: 1001,
        msg: '请重新登录'
      });
      return;
    }
    const flag = await validToekn.validToken(auth, ctx);
    if (flag !== '2') {
      switch (flag) {
        case '0':
          ctx.body = JSON.stringify({
            code: 1001,
            msg: '请重新登录'
          });
          break;
        case '1':
          ctx.body = JSON.stringify({
            code: 1024,
            msg: 'token失效'
          });
          break;
      }
      return;
    }
  }
  await next();
});

router.use('/miniApp/user', userRouter.routes(), userRouter.allowedMethods());
router.use('/miniApp/account', accountRouter.routes(), accountRouter.allowedMethods());

app.use(router.routes()).use(router.allowedMethods());

app.on('error', (err, ctx) => {
  ctx.body = '服务器繁忙, 请稍后再试';
  console.log('server err');
  console.log(err.stack);
  console.log('========');
  const emailContent = `
     <div style="margin: 0 auto; color: red;">
         <h1 style="text-align: center;">请注意服务器报错</h1>
         <p>${err.message}</p>
         <p>${err.stack}</p>
     </div>
    `;
  ctx.body = JSON.stringify({
    code: 1000,
    msg: '服务器错误'
  });
  sendEmail('WARN server err', emailContent);
});

app.listen(config.port, '0.0.0.0', () => {
  log.info('server is open on prot => ', config.port);
});
